<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8" />
    <title>Native C++ 功能调试</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no" />
    
    <!-- HarmonyOS 优化配置 -->
    <meta name="theme-color" content="#667eea" />
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="apple-mobile-web-app-status-bar-style" content="default" />
    
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            color: #333;
        }
        
        .app-container {
            min-height: 100vh;
            display: flex;
            flex-direction: column;
        }
        
        .header {
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(10px);
            color: white;
            padding: 16px;
            text-align: center;
            font-size: 20px;
            font-weight: 600;
            box-shadow: 0 2px 20px rgba(0,0,0,0.1);
        }
        
        .content {
            flex: 1;
            padding: 20px;
            overflow-y: auto;
        }
        
        .card {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 16px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 8px 32px rgba(0,0,0,0.1);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255, 255, 255, 0.2);
        }
        
        .card-title {
            font-size: 18px;
            font-weight: 600;
            margin-bottom: 16px;
            color: #333;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .input-group {
            margin-bottom: 16px;
        }
        
        .input-label {
            display: block;
            font-size: 14px;
            font-weight: 500;
            color: #555;
            margin-bottom: 8px;
        }
        
        .input-field {
            width: 100%;
            padding: 12px 16px;
            border: 2px solid #e1e5e9;
            border-radius: 8px;
            font-size: 16px;
            transition: all 0.3s ease;
            background: white;
        }
        
        .input-field:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }
        
        .textarea-field {
            min-height: 80px;
            resize: vertical;
        }
        
        .button-group {
            display: flex;
            gap: 12px;
            flex-wrap: wrap;
            margin-bottom: 16px;
        }
        
        .btn {
            padding: 12px 20px;
            border: none;
            border-radius: 8px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            gap: 8px;
            min-width: 120px;
            justify-content: center;
        }
        
        .btn-primary {
            background: #667eea;
            color: white;
        }
        
        .btn-primary:hover {
            background: #5a6fd8;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
        }
        
        .btn-secondary {
            background: #6c757d;
            color: white;
        }
        
        .btn-secondary:hover {
            background: #5a6268;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(108, 117, 125, 0.3);
        }
        
        .btn-success {
            background: #28a745;
            color: white;
        }
        
        .btn-success:hover {
            background: #218838;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(40, 167, 69, 0.3);
        }
        
        .btn-warning {
            background: #ffc107;
            color: #212529;
        }
        
        .btn-warning:hover {
            background: #e0a800;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(255, 193, 7, 0.3);
        }
        
        .btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none !important;
            box-shadow: none !important;
        }
        
        .result-box {
            background: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 8px;
            padding: 16px;
            margin-top: 16px;
            font-family: 'Courier New', monospace;
            font-size: 14px;
            line-height: 1.5;
            max-height: 200px;
            overflow-y: auto;
        }
        
        .result-box.success {
            background: #d4edda;
            border-color: #c3e6cb;
            color: #155724;
        }
        
        .result-box.error {
            background: #f8d7da;
            border-color: #f5c6cb;
            color: #721c24;
        }
        
        .loading {
            display: inline-block;
            width: 16px;
            height: 16px;
            border: 2px solid #ffffff;
            border-radius: 50%;
            border-top-color: transparent;
            animation: spin 1s ease-in-out infinite;
        }
        
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
        
        .status-indicator {
            display: inline-block;
            width: 12px;
            height: 12px;
            border-radius: 50%;
            margin-right: 8px;
        }
        
        .status-indicator.connected {
            background: #28a745;
        }
        
        .status-indicator.disconnected {
            background: #dc3545;
        }
        
        .info-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 12px;
            margin-top: 16px;
        }
        
        .info-item {
            background: #f8f9fa;
            padding: 12px;
            border-radius: 8px;
            border-left: 4px solid #667eea;
        }
        
        .info-label {
            font-size: 12px;
            color: #6c757d;
            font-weight: 500;
            margin-bottom: 4px;
        }
        
        .info-value {
            font-size: 16px;
            font-weight: 600;
            color: #333;
        }
        
        .test-all-btn {
            width: 100%;
            padding: 16px;
            font-size: 16px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 12px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            margin-top: 20px;
        }
        
        .test-all-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(102, 126, 234, 0.3);
        }
        
        .debug-log {
            background: #1e1e1e;
            color: #f8f8f2;
            padding: 16px;
            border-radius: 8px;
            font-family: 'Courier New', monospace;
            font-size: 12px;
            line-height: 1.4;
            max-height: 300px;
            overflow-y: auto;
            margin-top: 16px;
        }
        
        .log-entry {
            margin-bottom: 4px;
        }
        
        .log-timestamp {
            color: #6272a4;
        }
        
        .log-level-info {
            color: #8be9fd;
        }
        
        .log-level-error {
            color: #ff5555;
        }
        
        .log-level-success {
            color: #50fa7b;
        }
    </style>
</head>
<body>
    <div class="app-container">
        <div class="header">
            <span class="status-indicator" id="bridgeStatus"></span>
            🚀 Native C++ 功能调试
        </div>
        
        <div class="content">
            <!-- 连接状态卡片 -->
            <div class="card">
                <div class="card-title">🔗 连接状态</div>
                <div id="connectionStatus">检查中...</div>
                <button class="btn btn-primary" onclick="checkBridgeConnection()">
                    重新检查连接
                </button>
            </div>
            
            <!-- 加密功能测试 -->
            <div class="card">
                <div class="card-title">🔐 加密功能测试</div>
                
                <div class="input-group">
                    <label class="input-label">输入文本</label>
                    <input type="text" id="cryptoText" class="input-field" placeholder="请输入要加密的文本" value="Hello HarmonyOS!">
                </div>
                
                <div class="input-group">
                    <label class="input-label">加密密钥</label>
                    <input type="text" id="cryptoKey" class="input-field" placeholder="请输入加密密钥" value="mykey123">
                </div>
                
                <div class="button-group">
                    <button class="btn btn-primary" onclick="testEncrypt()">
                        <span id="encryptLoading" class="loading" style="display: none;"></span>
                        加密
                    </button>
                    <button class="btn btn-secondary" onclick="testDecrypt()">
                        <span id="decryptLoading" class="loading" style="display: none;"></span>
                        解密
                    </button>
                    <button class="btn btn-success" onclick="testHash()">
                        <span id="hashLoading" class="loading" style="display: none;"></span>
                        生成哈希
                    </button>
                </div>
                
                <div id="cryptoResult" class="result-box" style="display: none;"></div>
            </div>
            
            <!-- 压缩功能测试 -->
            <div class="card">
                <div class="card-title">📦 压缩功能测试</div>
                
                <div class="input-group">
                    <label class="input-label">输入数据</label>
                    <textarea id="compressionData" class="input-field textarea-field" placeholder="请输入要压缩的数据">AAAAAABBBBBBCCCCCCDDDDDD这是一个测试字符串，包含重复字符用于测试压缩效果。</textarea>
                </div>
                
                <div class="button-group">
                    <button class="btn btn-primary" onclick="testCompress()">
                        <span id="compressLoading" class="loading" style="display: none;"></span>
                        压缩
                    </button>
                    <button class="btn btn-secondary" onclick="testDecompress()">
                        <span id="decompressLoading" class="loading" style="display: none;"></span>
                        解压
                    </button>
                    <button class="btn btn-warning" onclick="testChecksum()">
                        <span id="checksumLoading" class="loading" style="display: none;"></span>
                        校验和
                    </button>
                </div>
                
                <div id="compressionResult" class="result-box" style="display: none;"></div>
            </div>
            
            <!-- 设备信息测试 -->
            <div class="card">
                <div class="card-title">📱 设备信息测试</div>
                
                <div class="button-group">
                    <button class="btn btn-primary" onclick="testCpuInfo()">
                        <span id="cpuLoading" class="loading" style="display: none;"></span>
                        CPU信息
                    </button>
                    <button class="btn btn-secondary" onclick="testMemoryInfo()">
                        <span id="memoryLoading" class="loading" style="display: none;"></span>
                        内存信息
                    </button>
                    <button class="btn btn-success" onclick="testPerformanceInfo()">
                        <span id="performanceLoading" class="loading" style="display: none;"></span>
                        性能信息
                    </button>
                </div>
                
                <div id="deviceInfoResult" class="info-grid" style="display: none;"></div>
            </div>
            
            <!-- 综合测试 -->
            <div class="card">
                <div class="card-title">🧪 综合测试</div>
                <button class="test-all-btn" onclick="runAllTests()">
                    <span id="allTestsLoading" class="loading" style="display: none;"></span>
                    运行所有测试
                </button>
                <div id="allTestsResult" class="result-box" style="display: none;"></div>
            </div>
            
            <!-- 调试日志 -->
            <div class="card">
                <div class="card-title">📋 调试日志</div>
                <button class="btn btn-secondary" onclick="clearLog()">清空日志</button>
                <div id="debugLog" class="debug-log"></div>
            </div>
        </div>
    </div>

    <script>
        // 全局变量
        let encryptedData = '';
        let compressedData = '';
        let harmonyBridge = null;
        
        // 日志功能
        function addLog(level, message) {
            const logContainer = document.getElementById('debugLog');
            const timestamp = new Date().toLocaleTimeString();
            const logEntry = document.createElement('div');
            logEntry.className = 'log-entry';
            logEntry.innerHTML = `<span class="log-timestamp">[${timestamp}]</span> <span class="log-level-${level}">[${level.toUpperCase()}]</span> ${message}`;
            logContainer.appendChild(logEntry);
            logContainer.scrollTop = logContainer.scrollHeight;
        }
        
        function clearLog() {
            document.getElementById('debugLog').innerHTML = '';
        }
        
        // 检查HarmonyBridge连接
        function checkBridgeConnection() {
            addLog('info', '检查HarmonyBridge连接状态...');
            
            const statusElement = document.getElementById('connectionStatus');
            const statusIndicator = document.getElementById('bridgeStatus');
            
            try {
                // 检查是否在HarmonyOS环境
                const isHarmonyOS = !!(window.HarmonyOS || navigator.userAgent.includes('HarmonyOS') || window.HarmonyBridge);
                
                if (isHarmonyOS && window.HarmonyBridge) {
                    harmonyBridge = window.HarmonyBridge;
                    statusElement.innerHTML = '✅ HarmonyBridge 已连接';
                    statusIndicator.className = 'status-indicator connected';
                    addLog('success', 'HarmonyBridge连接成功');
                    return true;
                } else {
                    statusElement.innerHTML = '❌ HarmonyBridge 未连接 (可能不在HarmonyOS环境中)';
                    statusIndicator.className = 'status-indicator disconnected';
                    addLog('error', 'HarmonyBridge连接失败');
                    return false;
                }
            } catch (error) {
                statusElement.innerHTML = `❌ 连接错误: ${error.message}`;
                statusIndicator.className = 'status-indicator disconnected';
                addLog('error', `连接检查出错: ${error.message}`);
                return false;
            }
        }
        
        // 调用Native方法的通用函数
        async function callNativeMethod(method, args = {}) {
            if (!harmonyBridge) {
                throw new Error('HarmonyBridge 未连接');
            }
            
            const message = {
                method: method,
                args: args,
                callbackId: Date.now().toString()
            };
            
            addLog('info', `调用Native方法: ${method}`);
            addLog('info', `参数: ${JSON.stringify(args)}`);
            
            try {
                const response = await harmonyBridge.handleMessage(JSON.stringify(message));
                const result = JSON.parse(response);
                
                if (!result.success) {
                    throw new Error(result.error || '调用失败');
                }
                
                addLog('success', `方法 ${method} 调用成功`);
                return result.data;
            } catch (error) {
                addLog('error', `方法 ${method} 调用失败: ${error.message}`);
                throw error;
            }
        }
        
        // 显示加载状态
        function showLoading(elementId, show = true) {
            const element = document.getElementById(elementId);
            if (element) {
                element.style.display = show ? 'inline-block' : 'none';
            }
        }
        
        // 显示结果
        function showResult(containerId, content, isError = false) {
            const container = document.getElementById(containerId);
            container.style.display = 'block';
            container.className = `result-box ${isError ? 'error' : 'success'}`;
            container.innerHTML = content;
        }
        
        // 加密功能测试
        async function testEncrypt() {
            const text = document.getElementById('cryptoText').value;
            const key = document.getElementById('cryptoKey').value;
            
            if (!text || !key) {
                showResult('cryptoResult', '请输入文本和密钥', true);
                return;
            }
            
            showLoading('encryptLoading', true);
            
            try {
                const result = await callNativeMethod('native.encryptString', { text, key });
                encryptedData = result.data;
                showResult('cryptoResult', `加密成功！\n加密结果: ${encryptedData}`);
            } catch (error) {
                showResult('cryptoResult', `加密失败: ${error.message}`, true);
            } finally {
                showLoading('encryptLoading', false);
            }
        }
        
        async function testDecrypt() {
            const key = document.getElementById('cryptoKey').value;
            
            if (!encryptedData || !key) {
                showResult('cryptoResult', '请先加密数据并输入密钥', true);
                return;
            }
            
            showLoading('decryptLoading', true);
            
            try {
                const result = await callNativeMethod('native.decryptString', { 
                    encryptedText: encryptedData, 
                    key 
                });
                showResult('cryptoResult', `解密成功！\n解密结果: ${result.data}`);
            } catch (error) {
                showResult('cryptoResult', `解密失败: ${error.message}`, true);
            } finally {
                showLoading('decryptLoading', false);
            }
        }
        
        async function testHash() {
            const text = document.getElementById('cryptoText').value;
            
            if (!text) {
                showResult('cryptoResult', '请输入文本', true);
                return;
            }
            
            showLoading('hashLoading', true);
            
            try {
                const result = await callNativeMethod('native.generateHash', { text });
                showResult('cryptoResult', `哈希生成成功！\n哈希值: ${result.data}`);
            } catch (error) {
                showResult('cryptoResult', `哈希生成失败: ${error.message}`, true);
            } finally {
                showLoading('hashLoading', false);
            }
        }
        
        // 压缩功能测试
        async function testCompress() {
            const data = document.getElementById('compressionData').value;
            
            if (!data) {
                showResult('compressionResult', '请输入要压缩的数据', true);
                return;
            }
            
            showLoading('compressLoading', true);
            
            try {
                const result = await callNativeMethod('native.compressData', { data });
                compressedData = result.data;
                const compressionRatio = ((result.compressedSize / result.originalSize) * 100).toFixed(2);
                
                showResult('compressionResult', 
                    `压缩成功！\n` +
                    `原始大小: ${result.originalSize} 字节\n` +
                    `压缩大小: ${result.compressedSize} 字节\n` +
                    `压缩比: ${compressionRatio}%\n` +
                    `压缩数据: ${compressedData}`
                );
            } catch (error) {
                showResult('compressionResult', `压缩失败: ${error.message}`, true);
            } finally {
                showLoading('compressLoading', false);
            }
        }
        
        async function testDecompress() {
            if (!compressedData) {
                showResult('compressionResult', '请先压缩数据', true);
                return;
            }
            
            showLoading('decompressLoading', true);
            
            try {
                const result = await callNativeMethod('native.decompressData', { 
                    compressedData 
                });
                showResult('compressionResult', `解压成功！\n解压结果: ${result.data}`);
            } catch (error) {
                showResult('compressionResult', `解压失败: ${error.message}`, true);
            } finally {
                showLoading('decompressLoading', false);
            }
        }
        
        async function testChecksum() {
            const data = document.getElementById('compressionData').value;
            
            if (!data) {
                showResult('compressionResult', '请输入数据', true);
                return;
            }
            
            showLoading('checksumLoading', true);
            
            try {
                const result = await callNativeMethod('native.calculateChecksum', { data });
                showResult('compressionResult', `校验和计算成功！\n校验和: ${result.checksum}`);
            } catch (error) {
                showResult('compressionResult', `校验和计算失败: ${error.message}`, true);
            } finally {
                showLoading('checksumLoading', false);
            }
        }
        
        // 设备信息测试
        async function testCpuInfo() {
            showLoading('cpuLoading', true);
            
            try {
                const result = await callNativeMethod('native.getCpuInfo');
                const data = result.data;
                
                document.getElementById('deviceInfoResult').style.display = 'grid';
                document.getElementById('deviceInfoResult').innerHTML = `
                    <div class="info-item">
                        <div class="info-label">CPU核心数</div>
                        <div class="info-value">${data.coreCount}</div>
                    </div>
                    <div class="info-item">
                        <div class="info-label">CPU架构</div>
                        <div class="info-value">${data.architecture}</div>
                    </div>
                    <div class="info-item">
                        <div class="info-label">CPU频率</div>
                        <div class="info-value">${data.frequencyGHz} GHz</div>
                    </div>
                `;
            } catch (error) {
                showResult('deviceInfoResult', `获取CPU信息失败: ${error.message}`, true);
            } finally {
                showLoading('cpuLoading', false);
            }
        }
        
        async function testMemoryInfo() {
            showLoading('memoryLoading', true);
            
            try {
                const result = await callNativeMethod('native.getMemoryInfo');
                const data = result.data;
                
                document.getElementById('deviceInfoResult').style.display = 'grid';
                document.getElementById('deviceInfoResult').innerHTML = `
                    <div class="info-item">
                        <div class="info-label">总内存</div>
                        <div class="info-value">${formatBytes(data.totalMemory)}</div>
                    </div>
                    <div class="info-item">
                        <div class="info-label">可用内存</div>
                        <div class="info-value">${formatBytes(data.freeMemory)}</div>
                    </div>
                    <div class="info-item">
                        <div class="info-label">已用内存</div>
                        <div class="info-value">${formatBytes(data.usedMemory)}</div>
                    </div>
                    <div class="info-item">
                        <div class="info-label">使用率</div>
                        <div class="info-value">${data.usagePercent.toFixed(2)}%</div>
                    </div>
                `;
            } catch (error) {
                showResult('deviceInfoResult', `获取内存信息失败: ${error.message}`, true);
            } finally {
                showLoading('memoryLoading', false);
            }
        }
        
        async function testPerformanceInfo() {
            showLoading('performanceLoading', true);
            
            try {
                const result = await callNativeMethod('native.getSystemPerformance');
                const data = result.data;
                
                document.getElementById('deviceInfoResult').style.display = 'grid';
                document.getElementById('deviceInfoResult').innerHTML = `
                    <div class="info-item">
                        <div class="info-label">运行时间</div>
                        <div class="info-value">${formatUptime(data.uptimeSeconds)}</div>
                    </div>
                    <div class="info-item">
                        <div class="info-label">1分钟负载</div>
                        <div class="info-value">${data.load1min.toFixed(2)}</div>
                    </div>
                    <div class="info-item">
                        <div class="info-label">5分钟负载</div>
                        <div class="info-value">${data.load5min.toFixed(2)}</div>
                    </div>
                    <div class="info-item">
                        <div class="info-label">15分钟负载</div>
                        <div class="info-value">${data.load15min.toFixed(2)}</div>
                    </div>
                    <div class="info-item">
                        <div class="info-label">进程数</div>
                        <div class="info-value">${data.processCount}</div>
                    </div>
                `;
            } catch (error) {
                showResult('deviceInfoResult', `获取性能信息失败: ${error.message}`, true);
            } finally {
                showLoading('performanceLoading', false);
            }
        }
        
        // 综合测试
        async function runAllTests() {
            showLoading('allTestsLoading', true);
            
            try {
                const result = await callNativeMethod('native.runTests');
                showResult('allTestsResult', 
                    `综合测试完成！\n\n测试结果:\n${JSON.stringify(result.results, null, 2)}`
                );
            } catch (error) {
                showResult('allTestsResult', `综合测试失败: ${error.message}`, true);
            } finally {
                showLoading('allTestsLoading', false);
            }
        }
        
        // 工具函数
        function formatBytes(bytes) {
            if (bytes === 0) return '0 Bytes';
            const k = 1024;
            const sizes = ['Bytes', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }
        
        function formatUptime(seconds) {
            const days = Math.floor(seconds / 86400);
            const hours = Math.floor((seconds % 86400) / 3600);
            const minutes = Math.floor((seconds % 3600) / 60);
            return `${days}天 ${hours}小时 ${minutes}分钟`;
        }
        
        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            addLog('info', 'Native C++ 调试页面已加载');
            checkBridgeConnection();
        });
    </script>
</body>
</html>